package com.css.zfzx.sjcj.modules.statistics.qhProbabilityEarthquakeDanger.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.pojo.QueryVo;
import com.css.zfzx.sjcj.modules.statistics.hdcActiveFault.service.HdcActiveFaultService;
import com.css.zfzx.sjcj.modules.statistics.qhProbabilityEarthquakeDanger.service.QhProbabilityEarthquakeDangerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/pc/qhProbabilityEarthquakeDanger")
public class QhProbabilityEarthquakeDangerController {
    @Autowired
    QhProbabilityEarthquakeDangerService service;

    ///pc/qhProbabilityEarthquakeDanger/findData
    @GetMapping("/findData")
    public RestResponse findData(QueryVo queryVo, HttpServletRequest req) {
        RestResponse response = null;
        String userId = ServerUtil.getUserId(req);
        try {
            int curPage = Integer.valueOf(req.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(req.getParameter(PlatformPageUtils.PAGE_SIZE));
            String sort = req.getParameter("sort");
            String order = req.getParameter("order");
            JSONObject list = service.find(queryVo, userId, curPage, pageSize, sort, order);
            response = RestResponse.succeed(list);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;

    /**
     * 数据对应附件展示
     */
    @GetMapping("/attachment-show")
    public RestResponse attachmentShow() {
        Set<String> attachmentName = service.findAttachmentName();
        File[] files = new File(uploadPath).listFiles();
        if (files == null || files.length<=0) {
            return RestResponse.fail("服务器无当前菜单对应附件");
        }
        List<String> realyName = new ArrayList<>();
        for (File f : files) {
            System.out.println(f.getName());
            for (String name : attachmentName) {
                if(f.getName().contains(name)){
                    realyName.add(f.getName());
                }
            }
        }
        System.out.println(realyName.size());
        return RestResponse.succeed(realyName);
    }

    /**
     * 根据附件名称下载附件
     *
     * @param response
     * @param response
     */
    @GetMapping("/attachment-download")
    public void attachmentDownload(HttpServletRequest request, HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        RestResponse<String> message = null;
        //获取到指定文件
        File file = new File(uploadPath+fileName);
        // 如果文件名存在，则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(DateFormat.getDateInstance().format(new Date())+"-"+fileName, "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                log.info("附件下载成功！");
            } catch (Exception e) {
                log.info("附件下载失败！");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {//对应文件不存在
            log.info("文件不存在");
        }
    }


    @GetMapping("/export")
    public void export(HttpServletRequest req, HttpServletResponse resp) {
        String userId = ServerUtil.getUserId(req);
        service.export(userId, resp);
    }

    /***
     * 系统自动质检
     * @param queryVo
     * @return
     */
    @PostMapping("/dataQualityCheck")
    public RestResponse dataQualityCheck(@RequestBody QueryVo queryVo) {
        RestResponse responseRest = null;
        JSONObject jsonObject = new JSONObject();
        try {
            service.dataQualityCheck(queryVo);
            jsonObject.put("message", "质检成功！");
            responseRest = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "质检失败!";
            responseRest = RestResponse.fail(errorMessage);
        }
        return responseRest;
    }

    @PostMapping("/dataReportPG")
    public RestResponse dataReportPG(@RequestBody QueryVo queryVo) {
        RestResponse responseRest = null;
        JSONObject jsonObject = new JSONObject();
        try{
            service.dataReportPG(queryVo);
            jsonObject.put("message", "质检成功！");
            responseRest = RestResponse.succeed(jsonObject);
        }catch (Exception e){
            String errorMessage = "质检失败!";
            responseRest = RestResponse.fail(errorMessage);
        }
        return responseRest;
    }
}
